package com.thirteenClassicsServer.service.impl;

import com.thirteenClassics.async.MarkServiceAsync;
import com.thirteenClassics.cache.JdbSentenceCache;
import com.thirteenClassics.context.BaseContext;
import com.thirteenClassics.dto.*;
import com.thirteenClassics.entity.Dictionary;
import com.thirteenClassics.entity.*;
import com.thirteenClassics.enumeration.ActionEnum;
import com.thirteenClassics.enumeration.MinorityEntityEnum;
import com.thirteenClassics.enumeration.OrderJdbFlagEnum;
import com.thirteenClassics.exception.BaseException;
import com.thirteenClassics.result.PageResult;
import com.thirteenClassics.vo.MarkCatalogQueryJdbVO;
import com.thirteenClassics.vo.MarkCatalogQuerySingleVO;
import com.thirteenClassics.vo.SentenceVO;
import com.thirteenClassicsServer.mapper.*;
import com.thirteenClassicsServer.service.IMarkService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.thirteenClassicsServer.service.impl.XmlParseService.toGetTableName;

@Slf4j
@Service
public class MarkServiceImpl implements IMarkService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private MarkMapper markMapper;
    @Resource
    private EntryMapper entryMapper;
    @Resource
    private SentenceMapper sentenceMapper;
    @Resource
    private SemanticMapper semanticMapper;
    @Resource
    private DictionaryMapper dictionaryMapper;
    @Resource
    private BookMapper bookMapper;
    @Resource
    private PictureMapper pictureMapper;
    @Resource
    private CatalogBookMapper catalogBookMapper;
    @Resource
    private CatalogMapper catalogMapper;
    @Resource
    private EntityMapper entityMapper;

    @Resource
    private ExplainMapper explainMapper;

    @Resource
    private SentenceLinkMapper sentenceLinkMapper;

    @Resource
    private OperationHistoryMapper operationHistoryMapper;

    @Resource
    private JdbSentenceCache jdbSentenceCache;

    @Resource
    private MarkServiceAsync markServiceAsync;

    // <editor-fold defaultstate="collapsed" desc="pageQueryMark 对照表标注分页查询">
    @Override
    public PageResult pageQueryMark(EntryPageQueryDTO entryPageQueryDTO) {
        entryPageQueryDTO.setJdbFlag(0L);
        List<Book> books = markMapper.pageMarkQuery(entryPageQueryDTO);

        List<BookDto> bookDtos = books.stream().map(book -> {
            BookDto bookDto = new BookDto();
            BeanUtils.copyProperties(book, bookDto);

            // 设置标志
            bookDto.setFlag(BookServiceImpl.judge(book.getBookLang(), BaseContext.getCurrentLang()) ? 1L : 0L);

            // 获取操作历史
            OperationHistory operationHistory = new OperationHistory();
            operationHistory.setBookId(book.getId());
            operationHistory.setUserId(BaseContext.getCurrentId());
            operationHistory.setAction(ActionEnum.MARKACTION.getCode());

            OperationHistory operationHistory1 = operationHistoryMapper.selectIndex(operationHistory);
            if (operationHistory1 != null) {
                bookDto.setIndex(operationHistory1.getIndex());
                bookDto.setSentenceIndex(operationHistory1.getSentenceIndex());
                bookDto.setParagraphIndex(operationHistory1.getSentenceIndex());
            }

            // 使用空格分隔字符串并转换为列表
            List<String> characterList = Arrays.asList(book.getBookLang().trim().split(" "));
            bookDto.setBookLang(characterList);

            return bookDto;
        }).collect(Collectors.toList());

        List<BookDto> sortedBooks = sortBooksByFlag(bookDtos);

        // 内存分页
        int startIndex = (entryPageQueryDTO.getPage() - 1) * entryPageQueryDTO.getPageSize();
        if (startIndex >= sortedBooks.size()) {
            return new PageResult(sortedBooks.size(), Collections.emptyList());
        }

        int endIndex = Math.min(startIndex + entryPageQueryDTO.getPageSize(), sortedBooks.size());
        return new PageResult(sortedBooks.size(), sortedBooks.subList(startIndex, endIndex));
    }

    public List<BookDto> sortBooksByFlag(List<BookDto> bookDtoList) {
        Comparator<BookDto> comparator = Comparator.comparing(BookDto::getFlag, Comparator.reverseOrder())
                .thenComparing(bookDto -> Optional.ofNullable(bookDto.getBookMarkTime()).orElse(LocalDateTime.MIN), Comparator.reverseOrder());

        return bookDtoList.stream()
                .sorted(comparator)
                .collect(Collectors.toList());
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="pageQueryMarkJdb 经典版标注分页查询">
    @Override
    public PageResult pageQueryMarkJdb(EntryPageQueryDTO entryPageQueryDTO) {
        entryPageQueryDTO.setJdbFlag(1L);
        List<Book> books = markMapper.pageMarkQuery(entryPageQueryDTO);

        List<BookDto> bookDtos = books.stream().map(book -> {
            BookDto bookDto = new BookDto();
            BeanUtils.copyProperties(book, bookDto);

            // 设置标志
            bookDto.setFlag(BookServiceImpl.judge(book.getBookLang(), BaseContext.getCurrentLang()) ? 1L : 0L);

            // 获取操作历史
            OperationHistory operationHistory = new OperationHistory();
            operationHistory.setBookId(book.getId());
            operationHistory.setUserId(BaseContext.getCurrentId());
            operationHistory.setAction(ActionEnum.MARKACTION.getCode());

            OperationHistory operationHistory1 = operationHistoryMapper.selectIndex(operationHistory);
            if (operationHistory1 != null) {
                bookDto.setIndex(operationHistory1.getIndex());
                bookDto.setSentenceIndex(operationHistory1.getSentenceIndex());
                bookDto.setParagraphIndex(operationHistory1.getSentenceIndex());
            }

            // 使用空格分隔字符串并转换为列表
            //List<String> characterList = Arrays.asList(book.getBookLang().trim().split(" "));
            // bookDto.setBookLang(characterList); // 如果需要，可以取消注释

            return bookDto;
        }).collect(Collectors.toList());

        List<BookDto> sortedBooks = sortBooksByFlag(bookDtos);

        // 内存分页
        int startIndex = (entryPageQueryDTO.getPage() - 1) * entryPageQueryDTO.getPageSize();
        if (startIndex >= sortedBooks.size()) {
            return new PageResult(sortedBooks.size(), Collections.emptyList());
        }

        int endIndex = Math.min(startIndex + entryPageQueryDTO.getPageSize(), sortedBooks.size());
        return new PageResult(sortedBooks.size(), sortedBooks.subList(startIndex, endIndex));
    }

    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="selectCatalogAndAll 经典版ALL查询">

    @Override
    @Cacheable(value = "JdbMarkCache", key = "'JdbMark-' + #markCatalogQueryDTO.bookId + '-' + #markCatalogQueryDTO"
            + ".bookName + '-' + #markCatalogQueryDTO.index + '-' + #markCatalogQueryDTO.sentenceIndex + '-' + "
            + "#markCatalogQueryDTO.paragraphIndex")
    public MarkCatalogQueryJdbVO selectCatalogAndAll(MarkCatalogQueryDTO markCatalogQueryDTO) {
        MarkCatalogQueryJdbVO markCatalogQueryJdbVO = new MarkCatalogQueryJdbVO();
        Book book = bookMapper.selectbookById(markCatalogQueryDTO.getBookId());
        if (book == null) {
            throw new BaseException("不存在书目");
        }

        CatalogQueryDTO catalogQueryDTO = new CatalogQueryDTO();
        BeanUtils.copyProperties(markCatalogQueryDTO, catalogQueryDTO);

        //得到所有的目录信息
        List<Catalog> list = catalogMapper.selectCatalogOrdersByName(catalogQueryDTO);

        markCatalogQueryJdbVO.setId(catalogQueryDTO.getIndex());
        markCatalogQueryJdbVO.setName(list.get(catalogQueryDTO.getIndex().intValue() - 1).getContents());
        markCatalogQueryJdbVO.setAncestors(list.get(catalogQueryDTO.getIndex().intValue() - 1).getAncestors());
        markCatalogQueryJdbVO.setTot((long) list.size());
        markCatalogQueryJdbVO.setCatalogId(list.get(catalogQueryDTO.getIndex().intValue() - 1).getId());

        CommonDTO commonDTO = new CommonDTO();
        commonDTO.setCatalogId(list.get(catalogQueryDTO.getIndex().intValue() - 1).getId());
        commonDTO.setBookId(markCatalogQueryDTO.getBookId());
        //根据书id和catalogid查到在catalog_book中的记录
        CatalogBook catalogBook = catalogBookMapper.selectCatalogBookAll(commonDTO);
        if (catalogBook == null) {
            throw new BaseException("书内容不存在");
        }


        markCatalogQueryJdbVO.setEntryId(catalogBook.getId());

        //经典版的所有句子
        Sentence sentence = new Sentence();
        sentence.setEntryId(catalogBook.getId());

        List<SentenceVO> sentenceVOS = jdbSentenceCache.queryJdbSentence(sentence);
        markCatalogQueryJdbVO.setJdbContent(sentenceVOS);

        //得到sentenceId
        SentenceSelectDYBDTO sentenceSelectDYBDTO3 = new SentenceSelectDYBDTO();
        sentenceSelectDYBDTO3.setEntryId(catalogBook.getId());
        sentenceSelectDYBDTO3.setSentenceIds(markCatalogQueryDTO.getSentenceIndex());
        sentenceSelectDYBDTO3.setParagraphIds(markCatalogQueryDTO.getParagraphIndex());
        List<Sentence> sentence3 = sentenceMapper.selectSentenceJdbId(sentenceSelectDYBDTO3);
        if (sentence3.isEmpty()) {
            return markCatalogQueryJdbVO;
        }
        Long sentenceId = sentence3.get(0).getSentenceId();

        SentenceSelectDYBDTO sentenceSelectDYBDTO2 = new SentenceSelectDYBDTO();

        //经典版的当前句子
        sentenceSelectDYBDTO2.setEntryId(catalogBook.getId());
        sentenceSelectDYBDTO2.setSentenceIds(markCatalogQueryDTO.getSentenceIndex());
        sentenceSelectDYBDTO2.setParagraphIds(markCatalogQueryDTO.getParagraphIndex());
        Sentence sentence1 = sentenceMapper.selectByEntryIDAndOrderJdb(sentenceSelectDYBDTO2);

        markCatalogQueryJdbVO.setSentence(sentence1.getSentence());
        markCatalogQueryJdbVO.setExplainS(sentence1.getExplainS());
        markCatalogQueryJdbVO.setFc(sentence1.getFc());


        List<Entity> entities = new ArrayList<>();
        entities = entityMapper.selectBySentenceId(sentenceId, Long.valueOf(1), markCatalogQueryDTO.getBookName());


        markCatalogQueryJdbVO.setEntities(entities);

        List<Explain> explanations = new ArrayList<>();
        explanations = explainMapper.selectBySentenceId(sentenceId, Long.valueOf(1), markCatalogQueryDTO.getBookName());


        markCatalogQueryJdbVO.setExplanations(explanations);
        return markCatalogQueryJdbVO;
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="saveJdb 经典版标注保存">
    //TODO 还需要判断最后一句
    @Override
    @Transactional
    @CacheEvict(value = "JdbMarkCache", key = "'JdbMark-' + #markJdbDto.bookId + '-' + #markJdbDto.bookName + '-' + "
            + "#markJdbDto.index + '-' + #markJdbDto.sentenceIds + '-' + #markJdbDto.paragraphIds")
    public void saveJdb(MarkJdbDto markJdbDto) {
        log.info("经典版标注保存:{}",markJdbDto);
        String lockKey = "LOCK_ENTRY" + "-" + markJdbDto.getEntryId() + "-" + markJdbDto.getSentenceIds();
        Book book = bookMapper.selectbookByEntryId(markJdbDto.getEntryId());
        String userName = userMapper.getUserNameById(BaseContext.getCurrentId());
        bookMapper.updateMarkTime(book.getId(), LocalDateTime.now(), userName);
        //得到sentenceId
        SentenceSelectDYBDTO sentenceSelectDYBDTO3 = new SentenceSelectDYBDTO();
        sentenceSelectDYBDTO3.setEntryId(markJdbDto.getEntryId());
        sentenceSelectDYBDTO3.setSentenceIds(markJdbDto.getSentenceIds());
        sentenceSelectDYBDTO3.setParagraphIds(markJdbDto.getParagraphIds());
        List<Sentence> sentence3 = sentenceMapper.selectSentenceJdbId(sentenceSelectDYBDTO3);
        if (sentence3.isEmpty()) {
            throw new BaseException("根据该章节id，段落序号和句子序号。在经典版中找不到对应句子");
        }
        Long sentenceId = sentence3.get(0).getSentenceId();

        synchronized (lockKey) {
            //更新字段
            markJdbDto.setBookOperator(String.valueOf(BaseContext.getCurrentId()));
            markJdbDto.setBookOptime(LocalDateTime.now());
            sentenceMapper.updateJdbSentece(markJdbDto);

            List<Entity> entities =
                    entityMapper.selectBySentenceId(sentenceId, Long.valueOf(1), markJdbDto.getBookName());
            if (!entities.isEmpty()) {
                entityMapper.deleteBySentenceId(sentenceId, Long.valueOf(1), markJdbDto.getBookName());
            }
            if (!markJdbDto.getEntities().isEmpty()) {
                for (Entity entity : markJdbDto.getEntities()) {
                    entity.setSentenceId(sentenceId);
                    entity.setBanben(Long.valueOf(1));
                    entity.setBookName(markJdbDto.getBookName());
                    entityMapper.insert(entity);
                }
            }


            List<Explain> explains =
                    explainMapper.selectBySentenceId(sentenceId, Long.valueOf(1), markJdbDto.getBookName());
            if (!explains.isEmpty()) {
                explainMapper.deleteBySentenceId(sentenceId, Long.valueOf(1), markJdbDto.getBookName());
            }
            if (!markJdbDto.getExplains().isEmpty()) {
                for (Explain explain : markJdbDto.getExplains()) {
                    explain.setSentenceId(sentenceId);
                    explain.setBanben(Long.valueOf(1));
                    explain.setBookName(markJdbDto.getBookName());
                    explainMapper.insert(explain);
                }
            }
        }
        markServiceAsync.selectJdbCatalogAndAllFlashCache(new MarkCatalogQueryDTO().builder()
                .index(markJdbDto.getIndex())
                .bookName(markJdbDto.getBookName())
                .bookId(markJdbDto.getBookId())
                .paragraphIndex(markJdbDto.getParagraphIds())
                .sentenceIndex(markJdbDto.getSentenceIds())
                .build());


    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="selectCatalogAndAllComp 对照版ALL查询">
    @Override
    public MarkCatalogQuerySingleVO selectCatalogAndAllComp(MarkCatalogQueryDTO markCatalogQueryDTO) {
//        log.info("对照版ALL查询:{}",markCatalogQueryDTO);
        MarkCatalogQuerySingleVO markCatalogQueryJdbVO = new MarkCatalogQuerySingleVO();
        Book book = bookMapper.selectbookById(markCatalogQueryDTO.getBookId());
        if (book == null) {
            throw new BaseException("不存在该书目");
        }

        CatalogQueryDTO catalogQueryDTO = new CatalogQueryDTO();
        BeanUtils.copyProperties(markCatalogQueryDTO, catalogQueryDTO);

        //得到所有的目录信息
        List<Catalog> list = catalogBookMapper.selectCatalogOrdersByNameAndId(catalogQueryDTO);

        markCatalogQueryJdbVO.setId(catalogQueryDTO.getIndex());
        markCatalogQueryJdbVO.setName(list.get(catalogQueryDTO.getIndex().intValue() - 1).getContents());
        markCatalogQueryJdbVO.setAncestors(list.get(catalogQueryDTO.getIndex().intValue() - 1).getAncestors());
        markCatalogQueryJdbVO.setTotVolume(Long.valueOf(list.size()));
        markCatalogQueryJdbVO.setCatalogId(list.get(catalogQueryDTO.getIndex().intValue() - 1).getId());
        markCatalogQueryJdbVO.setAlias(list.get(catalogQueryDTO.getIndex().intValue() - 1).getAlias());

        CommonDTO commonDTO = new CommonDTO();
        commonDTO.setCatalogId(list.get(catalogQueryDTO.getIndex().intValue() - 1).getId());
        commonDTO.setBookId(markCatalogQueryDTO.getBookId());
        //根据书id和catalogId查到在catalog_book中的记录 少语的目录记录
        CatalogBook catalogBook = catalogBookMapper.selectCatalogBookAllMinority(commonDTO);
        if (catalogBook == null) {
            throw new BaseException("该少语目录不存在");
        }

        markCatalogQueryJdbVO.setEntryId(catalogBook.getId());


        String catalogIds = catalogBook.getCatalogIds();

        int[] catalogIdss = parseNumbers(catalogIds);
        List<SentenceVO> sentences = new ArrayList<>();
        for (int catalogId : catalogIdss) {
            if (catalogId == 0) {
                continue;
            }
            int entryId = catalogBookMapper.selectEntryIdByCatalogId(catalogId);
            sentences.addAll(jdbSentenceCache.queryJdbSentence(Sentence.builder().entryId((long)entryId).build()));
        }

        SentenceSelectDYBDTO sentenceSelectDYBDTO3 = SentenceSelectDYBDTO.builder().entryId(catalogBook.getId())
                .sentenceIds(markCatalogQueryDTO.getSentenceIndex())
                .paragraphIds(markCatalogQueryDTO.getParagraphIndex()).build();
        //当前句 index 的对照版句子
        Sentence sentenceDZB = sentenceMapper.selectSentenceIdDZB(sentenceSelectDYBDTO3,
                toGetTableName(markCatalogQueryDTO.getBookName()));


        List<Long> sentenceLinks = new ArrayList<>();
        if (sentenceDZB != null) {
            //该对照版对应的所有经典版
            sentenceLinks = sentenceLinkMapper.selectSentenceId(sentenceDZB.getSentenceId(),
                     book.getId());
        }
        //List<JdbLink> jdb = new ArrayList<>();

        //判断当前经典版是否被选择
        for (SentenceVO sentence1 : sentences) {  //sentences为所有的经典版  TODO
            sentence1.setOrderJdbFlag(OrderJdbFlagEnum.NOORDERJDB.getCode());
            for (Long sentenceLink : sentenceLinks) {
                if (Objects.equals(sentence1.getSentenceId(), sentenceLink)) {
                    sentence1.setOrderJdbFlag(OrderJdbFlagEnum.ORDERJDB.getCode());//选择了经典版为1，没选择经典版为0
                    break;
                }
            }

            //给定经典版句子id，查找关联的对照版，赋予给经典版的关联属性
//            List<SentenceLink> selectjd =
//                    sentenceLinkMapper.selectjd(sentence1.getSentenceId(),
//                            markCatalogQueryDTO.getBookId());
//
//            if (selectjd.size() != 0) {
//                JdbLink jdbLink = new JdbLink();
//                jdbLink.setSentenceIds(selectjd.get(0).getSentenceIds());
//                jdbLink.setEntryId(sentenceMapper.getEntryIdBySentenceId(selectjd.get(0).getSentenceId()));
//                sentence1.setJdbLink(jdbLink);
//            }
//            //关联的对照版 是当前句子
//            if (sentence1.getJdbLink() != null && (sentence1.getJdbLink().getSentenceIds()
//                    == markCatalogQueryDTO.getSentenceIndex())) {//对照版已经被经典版选择
//                jdb.add(sentence1.getJdbLink());
//            }
        }
        markCatalogQueryJdbVO.setJdbContent(sentences);

        if (sentenceDZB == null) {
            return markCatalogQueryJdbVO;
        }
        Long sentenceId = sentenceDZB.getSentenceId();

        List<Sentence> sentences1 = new ArrayList<>();
        if(!sentenceLinks.isEmpty()){
            sentences1 = sentenceMapper.selectSentenceById(sentenceLinks);
        }
        //经典版的所有句子  TODO

        StringBuffer sentenceFinal = new StringBuffer();
        for (Sentence sentence1 : sentences1) {
            sentenceFinal.append(sentence1.getSentence());
        }
        if (sentenceDZB != null) {
            markCatalogQueryJdbVO.setSentence(sentenceFinal.toString());
            markCatalogQueryJdbVO.setSentence1(sentenceDZB.getSentence());
            markCatalogQueryJdbVO.setSentenceld1(sentenceDZB.getSentenceld1());
            markCatalogQueryJdbVO.setSentence2(sentenceDZB.getSentence2());
            markCatalogQueryJdbVO.setSentenceld2(sentenceDZB.getSentenceld2());
            markCatalogQueryJdbVO.setSentencedz(sentenceDZB.getSentenceDz());
            markCatalogQueryJdbVO.setExplainS(sentenceDZB.getExplainS());
            markCatalogQueryJdbVO.setManwengld(sentenceDZB.getManwengLd());
            markCatalogQueryJdbVO.setFc1(sentenceDZB.getFc1());
            markCatalogQueryJdbVO.setFc2(sentenceDZB.getFc2());
        }


        List<Entity> entities = new ArrayList<>();
        List<Explain> explains = new ArrayList<>();
        StringBuffer stringBuffer = new StringBuffer();
        //其他书本的经典版句子  与 完整经典版句子对接
        //得到完整经典版句子的entryId先
        for (Sentence sentence1 : sentences1) {
            Long entryId = sentence1.getEntryId();
            Long catalogId = catalogBookMapper.selectCatelogIdById(entryId);
            Long bookId = bookMapper.selectJdbBookIdByName(markCatalogQueryDTO.getBookName());
            BookIdAndCatalogDTO bookIdAndCatalogDTO = new BookIdAndCatalogDTO();
            bookIdAndCatalogDTO.setCatalogId(catalogId);
            bookIdAndCatalogDTO.setBookId(bookId);
            Long entryIdJdb = catalogBookMapper.selectEntryIdByBookIdAndCatalogId(bookIdAndCatalogDTO);
            Long sentenceIdJdb = sentenceMapper.selectSentenceIdJdbByEntryIdAndSentenceIdsAndParagraphIds(entryIdJdb,
                    sentence1.getSentenceIds(), sentence1.getParagraphIds());
            List<Entity> entities1 =
                    entityMapper.selectBySentenceId(sentenceIdJdb, Long.valueOf(1), markCatalogQueryDTO.getBookName());
            entities.addAll(entities1);
            List<Explain> explains1 =
                    explainMapper.selectBySentenceId(sentenceIdJdb, Long.valueOf(1), markCatalogQueryDTO.getBookName());
            explains.addAll(explains1);
            String explain = sentenceMapper.selectexplainSJdbByEntryIdAndSentenceIdsAndParagraphIds(entryIdJdb,
                    sentence1.getSentenceIds(), sentence1.getParagraphIds());
            stringBuffer.append(explain);
        }
        markCatalogQueryJdbVO.setEntitiesJdb(entities);
        markCatalogQueryJdbVO.setExplanations(explains);
        markCatalogQueryJdbVO.setExplainsJdb(stringBuffer.toString());


        List<Dictionary> dictionaries =
                dictionaryMapper.selectBySentenceId(sentenceId, markCatalogQueryDTO.getBookName());
        markCatalogQueryJdbVO.setDictionaries(dictionaries);


        List<Entity> entities1 =
                entityMapper.selectBySentenceId(sentenceId, MinorityEntityEnum.MINORITYENTITY1.getCode(), markCatalogQueryDTO.getBookName());
        markCatalogQueryJdbVO.setEntities1(entities1);
        List<Entity> entities2 =
                entityMapper.selectBySentenceId(sentenceId, MinorityEntityEnum.MINORITYENTITY2.getCode(), markCatalogQueryDTO.getBookName());
        markCatalogQueryJdbVO.setEntities2(entities2);

        List<AllSentence> allSentences = new ArrayList<>();
        allSentences = sentenceMapper.selectAllSentence(catalogBook.getId(),
                toGetTableName(markCatalogQueryDTO.getBookName()));
        markCatalogQueryJdbVO.setAllSentences(allSentences);
        markCatalogQueryJdbVO.setTot((long) allSentences.size());


        return markCatalogQueryJdbVO;
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="saveComp 对照版保存">

    @Override
    @Transactional
    public void saveComp(MarkCompDto markCompDto) {
//        log.info("对照版标注{}", markCompDto);
        Book book = bookMapper.selectMinorityBookByEntryId(markCompDto.getEntryId());
        String userName = userMapper.getUserNameById(BaseContext.getCurrentId());
//        log.info("更新标注时间:bookId={}，time={}，userName={}", book.getId(), LocalDateTime.now(), userName);
        bookMapper.updateMarkTime(book.getId(), LocalDateTime.now(), userName);
        //得到sentenceId
        SentenceSelectDYBDTO sentenceSelectDYBDTO3 = SentenceSelectDYBDTO.builder().entryId(markCompDto.getEntryId())
                .sentenceIds(markCompDto.getSentenceIds()).paragraphIds(markCompDto.getParagraphIds()).build();
        Sentence sentence3 =
                sentenceMapper.selectSentenceIdDZB(sentenceSelectDYBDTO3, toGetTableName(markCompDto.getBookName()));
        if (sentence3 == null || sentence3.getSentenceId() == null) {
            throw new BaseException("Sentence is null or sentenceId is null.");
        }
        Long sentenceId = sentence3.getSentenceId();

        markCompDto.setBookOperator(String.valueOf(BaseContext.getCurrentId())); //标注只存id
        markCompDto.setBookOptime(LocalDateTime.now());

//        log.info("更新句子标注信息{}，{}", markCompDto, toGetTableName(markCompDto.getBookName()));
        log.info("更新句子标注信息:userId={}，userName={}, time={}, updateTable={}, bookId={}",
                markCompDto.getBookOperator(), userName, markCompDto.getBookOptime(), toGetTableName(markCompDto.getBookName()), book.getId());

        sentenceMapper.updateCompSentece(markCompDto, toGetTableName(markCompDto.getBookName()));

        List<Dictionary> dictionaries = dictionaryMapper.selectBySentenceId(sentenceId, markCompDto.getBookName());
        if (!dictionaries.isEmpty()) {
            log.info("删除字典:sentenceId={}，bookName={}", sentenceId, markCompDto.getBookName());
            dictionaryMapper.deleteBySentenceId(sentenceId, markCompDto.getBookName());
        }

        markCompDto.getDictionaries().stream()
                .filter(dictionary -> dictionary != null) // 可选：确保没有null值进入数据库
                .peek(dictionary -> { // 设置属性
                    dictionary.setBookName(markCompDto.getBookName());
                    dictionary.setSentenceId(sentenceId);
                })
                .forEach(dictionary -> dictionaryMapper.insert(dictionary)); // 插入数据库


        List<Entity> entities =
                entityMapper.selectBySentenceId(sentenceId, MinorityEntityEnum.MINORITYENTITY1.getCode(), markCompDto.getBookName());
        if (entities != null && !entities.isEmpty()) {
            entityMapper.deleteBySentenceId(sentenceId, MinorityEntityEnum.MINORITYENTITY1.getCode(), markCompDto.getBookName());
        }
        markCompDto.getEntities1().stream()
                .filter(entity -> entity != null)
                .peek(entity -> {
                    entity.setSentenceId(sentenceId);
                    entity.setBanben(MinorityEntityEnum.MINORITYENTITY1.getCode());
                    entity.setBookName(markCompDto.getBookName());
                })
                .forEach(entity -> entityMapper.insert(entity));

        List<Entity> entities2 =
                entityMapper.selectBySentenceId(sentenceId, MinorityEntityEnum.MINORITYENTITY2.getCode(), markCompDto.getBookName());
        if (!entities2.isEmpty()) {
            entityMapper.deleteBySentenceId(sentenceId, MinorityEntityEnum.MINORITYENTITY2.getCode(), markCompDto.getBookName());
        }
        markCompDto.getEntities2().stream()
                .filter(entity -> entity != null)
                .peek(entity -> {
                    entity.setSentenceId(sentenceId);
                    entity.setBanben(MinorityEntityEnum.MINORITYENTITY2.getCode());
                    entity.setBookName(markCompDto.getBookName());
                })
                .forEach(entity -> entityMapper.insert(entity));


    }
    // </editor-fold>
    public int[] parseNumbers(String input) {
        String[] parts = input.split("[,，]"); // 按英文逗号或中文逗号分割字符串
        int[] numbers = new int[parts.length];
        for (int i = 0; i < parts.length; i++) {
            numbers[i] = Integer.parseInt(parts[i]); // 转换成整数
        }
        return numbers;
    }

}
